/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccstore.servlet;

import it.unitn.science.matr155863_148346_145963.bccstore.DBManager;
import it.unitn.science.matr155863_148346_145963.bccstore.items.Product;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author berto
 */
public class SearchProductsSRV extends HttpServlet {

    private DBManager db;
    private static Logger log = Logger.getLogger(SearchProductsSRV.class);
    
    @Override
    public void init() throws UnavailableException{
            db=(DBManager)super.getServletContext().getAttribute("db_manager");
    }
    
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        PrintWriter out = response.getWriter();
        try {
            String categoryStr=request.getParameter("category");
            Integer category=null;
            if((categoryStr!=null)&&(!categoryStr.equals(""))){
                try{
                  category=Integer.parseInt(categoryStr);
                }catch(Exception ex){
                    out.println("You have an error on category field");
                }
            }
            Float price=null;;
            String priceStr=request.getParameter("price");
            if((priceStr!=null)&&(!priceStr.equals(""))){
                try{
                    price=Float.parseFloat(priceStr);
                }catch(Exception ex){
                    out.println("You have an error on price field");
                }
            }
            String name=request.getParameter("name");
            if((name!=null)&&(!name.equals(""))){
                name=null;
            }
            String seller=request.getParameter("seller");
            if(seller!=null){
                while(seller.startsWith(" ")){
                    seller=seller.substring(1);
                }
                while(seller.endsWith(" ")){
                    seller=seller.substring(seller.length()-1);
                }
                if(seller.equals("")){
                    seller=null;
                }
            }
            HashSet<Product> products=db.searchProducts(name,category,price,seller,null);
            if(products.isEmpty()){
                out.println("<h2>No products found</h2>");
            }else{
                out.println("<h2>Products found</h2>");
                for(Product p:products){
                    out.println("<div class=\"content\">");
                    out.println("<h3>"+p.getName()+"</h3>");
                    out.println("<img src=\""+request.getContextPath()+"/images/products/"+p.getImageName()+"\"/>");
                    out.println("<div class=\"details\">");
                    out.println("<h4>Price:</h4><p>"+p.getPrice()+" euro ;</p>");
                    out.println("<h4>Quantity:</h4><p>"+p.getQuantity()+" "+p.getUmName()+" ;</p>");
                    out.println("<h4>Description:</h4><p>"+p.getHumanDescription()+" ;</p>");
                    out.println("<a href=\""+response.encodeURL(request.getContextPath()+"/contents/user/BuyProduct?id="+p.getId())+"\" >Details</a>");
                    out.println("</div>");
                    out.println("</div>");
                }
            }
        }catch(Exception ex){
            log.error(ex);
            RequestDispatcher dispatcher=request.getRequestDispatcher("/contents/public/errorPage.html");
            dispatcher.include(request, response);
        } finally {    
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    
}
